/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.InputStream;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;

/**
 *
 * @author Administrator
 */
public class BackgroundMusic extends GameCanvas implements Runnable {

    //midlet
    private TestMIDlet midlet;
    private Display display;
    private boolean running = false;
    //speed 
    private int speedGame = 200;
    Player audioPlayer01;
    private long time = 0;
    private int tSound = 0;

    public BackgroundMusic(TestMIDlet midlet) {
        super(false);
        setFullScreenMode(true);

        this.midlet = midlet;

        try {
            InputStream in = getClass().getResourceAsStream("/attack.mid");
            audioPlayer01 = Manager.createPlayer(in, "audio/midi");

        } catch (IOException ex) {
        } catch (MediaException ex) {
        }

    }

    //start thread
    public void start() {
        running = true;
        Thread t = new Thread(this);
        t.start();
        playSound();
    }

    public void playSound(){
        try {
            audioPlayer01.start();           
        } catch (MediaException ex) {
        }
    }
    //game loop
    public void run() {
        Graphics g = getGraphics();
        while (running) {
            tSound++;
            time = System.currentTimeMillis();
            repaint();
            serviceRepaints();
            time = speedGame - (System.currentTimeMillis() - time) ;
            
            // look for keypress
            //checkForCollision();
            
             if(audioPlayer01.getState() == audioPlayer01.CLOSED){
                 System.out.println("BG Closed!");
                midlet.startSound();
            }
            System.out.println(tSound);
            if(tSound==9){
                tSound = 0;
                stop();
                midlet.startSound();                
            }
            //System.out.println(time);
            drawDisplay(g);
            try {
                Thread.sleep((time < 0 ? 0 : time));
            } catch (InterruptedException ie) {
            }
        }
    }

    public void stop() {
        running = false;
    }

    protected void drawDisplay(Graphics g) {
        g.setColor(0xffccff);
        g.fillRect(0, 0, getWidth(), getHeight());
        flushGraphics();
    }

}
